/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *          http://www.apexes.net
 */
package net.apexes.commons.lang.ext;

import net.apexes.commons.lang.ProcessIdentifier;

import java.security.SecureRandom;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class JseProcessIdentifier implements ProcessIdentifier {

    private final short processId;

    public JseProcessIdentifier() {
        this.processId = myPid();
    }

    @Override
    public short processId() {
        return processId;
    }

    public static short myPid() {
        short processId;
        try {
            String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
            if (processName.contains("@")) {
                processId = (short) Integer.parseInt(processName.substring(0, processName.indexOf('@')));
            } else {
                processId = (short) java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
            }
        } catch (Throwable t) {
            processId = (short) new SecureRandom().nextInt();
        }
        return processId;
    }
}
